package cn.csg.iotplatform.module.system.util;

import cn.csg.iotplatform.framework.common.util.collection.CollectionUtils;
import cn.csg.iotplatform.framework.common.util.collection.MapUtils;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import dm.jdbc.util.StringUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备中心接口通用请求类
 *
 * @author : sz
 * @date : 2024/5/15 14:37
 */
@Data
@Slf4j
@Component
public class EqtCenterUtil {

    @Value("${iot.eqt-center.app-id}")
    private  String id;

    @Value("${iot.eqt-center.app-key}")
    private  String key;

    private static String appId;
    private static String appKey;


    @PostConstruct
    public void init() {
        appId = id;
        appKey = key;
    }


    /**
     * 共库post-json请求头
     */
    public static Map<String, Object> doPostJsonHeader(String paramsJson){
        // 生成随机数
        String nonce = RandomStringUtils.randomAlphanumeric(6);
        // 生成时间戳签名
        long timestamp = System.currentTimeMillis();
        // 对请求参数进行sha256加密
        String params = sha256(paramsJson);
        // 创建签名参数
        Map<String, Object> map = new TreeMap<>();
        map.put("appId", appId);
        map.put("nonce", nonce);
        map.put("timestamp", timestamp);

        log.info("appId-->{}，appKey-->{}", appId, appKey);

        // 如请求参数为空则不需要加入该参数
        if (StringUtil.isNotEmpty(paramsJson)) {
            map.put("params", params);
        }
        // 对签名参数进行URL格式拼接
        String paramsSort = map.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        // 对签名参数进行sha256加密
        String sign = sha256(paramsSort + "&appKey=" + appKey);

        Map<String, Object> headersMap = new HashMap<>();
        headersMap.put("Content-Type", "application/json;charset=utf-8");
        headersMap.put("X-AppId", appId);
        headersMap.put("X-Timestamp", String.valueOf(timestamp));
        headersMap.put("X-Nonce", nonce);
        headersMap.put("X-Sign", sign);

        headersMap.put("bureauCode", "0301");

        return headersMap;
    }


    /**
     * 共库post-json请求头
     */
    public static Map<String, Object> doFormDataPostJsonHeader(String paramsJson){
        // 生成随机数
        String nonce = RandomStringUtils.randomAlphanumeric(6);
        // 生成时间戳签名
        long timestamp = System.currentTimeMillis();
        // 对请求参数进行sha256加密
        String params = sha256(paramsJson);
        // 创建签名参数
        Map<String, Object> map = new TreeMap<>();
        map.put("appId", appId);
        map.put("nonce", nonce);
        map.put("timestamp", timestamp);

        // 如请求参数为空则不需要加入该参数
        if (StringUtil.isNotEmpty(paramsJson)) {
            map.put("params", params);
        }
        // 对签名参数进行URL格式拼接
        String paramsSort = map.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        // 对签名参数进行sha256加密
        String sign = sha256(paramsSort + "&appKey=" + appKey);

        Map<String, Object> headersMap = new HashMap<>();
        headersMap.put("Content-Type", "multipart/form-data");
        headersMap.put("X-AppId", appId);
        headersMap.put("X-Timestamp", String.valueOf(timestamp));
        headersMap.put("X-Nonce", nonce);
        headersMap.put("X-Sign", sign);

        headersMap.put("bureauCode", "0301");

        return headersMap;
    }


    /**
     * 生成sha256
     *
     * @param data 加密数据
     * @return
     */
    public static String sha256(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes());
            byte[] digest = messageDigest.digest();
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < digest.length; i++) {
                String hex = Integer.toHexString(0xff & digest[i]);
                if (hex.length() == 1) {
                    stringBuffer.append('0');
                }
                stringBuffer.append(hex);
            }
            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
